#include <iostream>
#include "StartScreen.h"
#include "SelectModeScreen.h"
#include "MainWindow.h"

using namespace SDL::UTILS;

MainWindow::MainWindow() : AWindow(),
	m_quit(false)
{
	m_currentScreen.Screen = NULL;
	m_currentScreen.Args = NULL;
}

MainWindow::~MainWindow()
{
	m_screens.Clear();
}

int MainWindow::Exec()
{
	int tempsPrecedent = 0, tempsActuel = 0, delay = 10;
	this->InitStart();

	while (!m_quit)
	{
		tempsActuel = SDL_GetTicks();
		if (tempsActuel - tempsPrecedent > delay)
		{
			while (SDL_PollEvent(&m_event))
			{
				switch (m_event.type)
				{
				case SDL_QUIT:
					m_quit = true;
					break ;

				default:
					break ;
				}
				m_screens.Exec(NULL);
			}

			m_screens.Manage(NULL);

			m_screens.Draw(NULL);
			SDL_Flip(m_screen);

			if (m_currentScreen.Args->Value != 0)
				(this->*m_currentScreen.Finished)();
			tempsPrecedent = tempsActuel;
		}
		else
			SDL_Delay(delay - (tempsActuel - tempsPrecedent));
	}
	return (EXIT_SUCCESS);
}

void MainWindow::InitStart()
{
	m_currentScreen.Screen = new StartScreen();
	m_currentScreen.Args = new StartArgs(m_screen, &m_event);
	m_currentScreen.Finished = &MainWindow::StartFinished;
	m_screens.Add("start", m_currentScreen.Screen, StartScreen::Manage, m_currentScreen.Args);
}

void MainWindow::StartFinished()
{
	switch (m_currentScreen.Args->Value)
	{
	case 1:
		m_screens.Remove("start");
		this->InitSelectMode();
		break ;

	default:
		break ;
	}
}

void MainWindow::InitSelectMode()
{
	m_currentScreen.Screen = new SelectModeScreen();
	m_currentScreen.Args = new SelectModeArgs(m_screen, &m_event);
	m_currentScreen.Finished = &MainWindow::SelectModeFinished;
	m_screens.Add("selectmode", m_currentScreen.Screen, SelectModeScreen::Manage, m_currentScreen.Args);
}

void MainWindow::SelectModeFinished()
{
	switch (m_currentScreen.Args->Value)
	{
	case 1:
		m_screens.Remove("selectmode");
		this->InitStart();
		break ;

	default:
		break ;
	}
}
